%%%----------------------------------------------------------------------------------------------------
%%%  Description - This module is called to parse the XML request send by the client. This module is 
%%%  also used to parse the configuration file
%%%----------------------------------------------------------------------------------------------------

-module(parse_xml).
-include("../include/xmerl.hrl").
-include("../include/b2bua.hrl").

-import(xmerl_xs, [ xslapply/2, value_of/1, select/2, built_in_rules/2 ]).

-export([parse/1, process_xml/1, template/1]).

parse(XML_String) ->
    case catch xmerl_scan:string(XML_String) of
        {'EXIT', _} ->
            error;
        {XML_Content, _} ->
            process_xml(XML_Content);
        _ ->
            error
    end.

process_xml(XML_Content) -> 
	template(XML_Content). 

template(E = #xmlElement{name='talk_request'}) ->
	xslapply(fun template/1, E);

template(E = #xmlElement{parents=[{'talk_request', _}|_], name='register'}) ->
	{register, #register{userid = xslapply(fun template/1, select("@userid", E)), password =  xslapply(fun template/1, select("@password", E))}};

template(E = #xmlElement{parents=[{'talk_request', _}|_], name='invite'}) ->
	{invite, #invite{to = xslapply(fun template/1, select("@to", E))}};

template(E = #xmlElement{parents=[{'talk_request', _}|_], name='cancel'}) ->
	{cancel, #cancel{to = xslapply(fun template/1, select("@to", E))}};

template(E = #xmlElement{parents=[{'talk_request', _}|_], name='accept'}) ->
	{accept, #accept{from = xslapply(fun template/1, select("@from", E))}};

template(E = #xmlElement{parents=[{'talk_request', _}|_], name='reject'}) ->
	{reject, #reject{from = xslapply(fun template/1, select("@from", E))}};

template(E = #xmlElement{parents=[{'talk_request', _}|_], name='bye'}) ->
	{bye, #bye{to = xslapply(fun template/1, select("@to", E))}};

template(E)->
    built_in_rules(fun template/1, E). 
